package com.mango.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/7/21 22:26
 * 邮箱客户端的工具类
 */
    @Component
    public class MailClient {

        private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

        /**
         * 发送邮件的核心组件
         */
        @Autowired
        private JavaMailSender mailSender;
        /**
         * 邮件发件人
         * 这里是从application.yml中取得值springboot 中可以使用@Value 来获取到yml文件中的值 spring.mail.username 就是他的key
         */
        @Value("${spring.mail.username}")
        private String from;

        /** 发送邮件的方法
         * @param to        发送给谁
         * @param subject   邮件主题
         * @param content   邮件内容
         */
        public void sendMail(String to,String subject,String content){
            try {
                //创建一个发送邮件的类
                MimeMessage message = mailSender.createMimeMessage();
                //使用发送邮件的帮助类
                MimeMessageHelper helper = new MimeMessageHelper(message);
                //发送人
                helper.setFrom(from);
                //接收人
                helper.setTo(to);
                //发送的主题
                helper.setSubject(subject);
                //以html的形式的邮件内容
                helper.setText(content,true);
                //发送邮件
                mailSender.send(helper.getMimeMessage());
            } catch (MessagingException e) {
                logger.error("发送邮件失败"+e.getMessage());
            }
        }
    }
